package com.codi.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.codi.base.util.EqualsUtil;
import com.codi.base.util.StringUtil;
import com.codi.bus.constant.GlobalConstant;
import com.codi.bus.constant.RuleConstant;
import com.codi.bus.core.dao.OrganAgentDao;
import com.codi.bus.core.domain.*;
import com.codi.bus.core.resultModel.BaseListResult;
import com.codi.bus.core.resultModel.BaseResult;
import com.codi.bus.core.resultModel.FundNetValueResult;
import com.codi.bus.core.service.FundDetailService;
import com.codi.bus.core.service.LookupService;
import com.codi.bus.core.service.QueryService;
import com.codi.bus.core.service.UserService;
import com.codi.bus.core.service.model.AccountModel;
import com.codi.bus.core.service.model.OrganBabyModel;
import com.codi.bus.core.service.organ.OrganBabyService;
import com.codi.bus.core.service.organ.OrganBankService;
import com.codi.bus.core.service.organ.OrganProfileService;
import com.codi.bus.core.vo.OrganAgentVo;
import com.codi.bus.core.vo.OrganBabyVo;
import com.codi.bus.core.vo.OrganBankVo;
import com.codi.bus.exception.BaseException;
import com.codi.fcloud.ufx.HsResponseUtil;
import com.codi.fcloud.ufx.constant.HSOutputParameterNames;
import com.codi.message.constant.ErrorConstant;
import com.codi.message.util.MessageUtil;
import com.codi.trade.service.TradeAccountAddAcctService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author lvgo
 * @version 1.0
 * @Description: 机构后台
 * @date 2018/5/8 17:09
 */
@Slf4j
@Controller
@ResponseBody
@RequestMapping("/admin/organ")
public class OrganAdminController {

    @Resource
    private OrganBankService organBankService;
    @Resource
    private OrganProfileService organProfileService;
    @Resource
    private OrganAgentDao organAgentDao;
    @Resource
    private UserService userService;
    @Resource
    private QueryService queryService;
    @Resource(name = "tradeAccountAddAcctService")
    private TradeAccountAddAcctService tradeAccountAddAcctService;
    @Resource
    private OrganBabyService organBabyService;
    @Resource
    private LookupService lookupService;
    @Resource
    private FundDetailService fundDetailService;

    /**
     * 设置推荐企业宝
     *
     * @param fundCode
     * @return
     */
    @GetMapping("/setRecommend")
    public BaseResult recommendOrganBao(String fundCode) {
        BaseResult result = new BaseResult();
        try {
            organBabyService.setRecommendOrganBaby(fundCode);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorMessage(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 后台获取企业宝数据 ，分页
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/getOrganBabies")
    public BaseResult getOrganBabies(Integer pageIndex, Integer pageSize) {
        BaseListResult baseListResult = new BaseListResult();
        ArrayList<OrganBabyVo> organBabyVos = new ArrayList<>();
        OrganBabyModel commentBaby = organBabyService.getManageComment();

        List<Lookup> lookups = lookupService.getOrganBabies(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);

        lookups.forEach(lookup -> {
            String ruleLimitValue = lookup.getRuleLimitValue();
            String minMoney = "";
            String reminder = "";
            Boolean isRecommend = false;
            if (com.codi.bus.util.LookupUtil.isJSONObject(ruleLimitValue)) {
                JSONObject father = JSONObject.parseObject(ruleLimitValue);
                JSONObject child = father.getJSONObject("org");
                minMoney = child.getString("minMoney");
                reminder = child.getString("reminder");
            }
            if (commentBaby != null && commentBaby.getFundCode().equals(lookup.getRuleValue())) {
                isRecommend = true;
            }
            OrganBabyVo babyVo = OrganBabyVo.builder()
                .fundCode(lookup.getRuleValue())
                .fundName(lookup.getRuleText())
                .minValue(minMoney)
                .reminder(reminder)
                .isValid(lookup.getRuleValid())
                .isRecommend(isRecommend).build();
            organBabyVos.add(babyVo);
        });


        ArrayList<OrganBabyVo> resultOrganBabies = new ArrayList<>();
        for (int i = 0; i < organBabyVos.size(); i++) {
            if (i >= (pageIndex - 1) * pageSize && i < pageSize * pageIndex) {
                resultOrganBabies.add(organBabyVos.get(i));
            }
        }
        baseListResult.setTotalCount((long) organBabyVos.size());
        baseListResult.setResult(resultOrganBabies);

        return baseListResult;
    }

    /**
     * 企业宝上/下线
     * <p>
     * 1上线 0下线
     *
     * @param fundCode
     * @param state
     * @return
     */
    @GetMapping("/isValid")
    public BaseResult organBabyIsValid(String fundCode, Integer state) {
        BaseResult baseResult = new BaseResult();
        try {
            organBabyService.babyIsValid(fundCode, state);
        } catch (BaseException e) {
            baseResult.setSuccess(false);
            baseResult.setErrorMessage(e.getMessage());
        }
        return baseResult;
    }

    /**
     * 获取上线的企业宝
     *
     * @return
     */
    @GetMapping("/getOnline")
    public BaseResult getOnlineOrganBabies() {
        List<OrganBabyVo> organBabyVos = organBabyService.getOnlineBabies();
        BaseResult baseResult = new BaseResult();
        baseResult.setResult(organBabyVos);
        return baseResult;
    }


    /**
     * 后台添加企业宝
     *
     * @param fundCode
     * @param minValue
     * @param reminder
     * @return
     */
    @PostMapping("/edit/organBaby")
    public BaseResult editOrganBaby(Integer isEdit, String fundCode, String minValue, String reminder) {
        BaseResult result = new BaseResult();
        FundNetValueResult fundNetValue = fundDetailService.getFundNetValue(fundCode, new Date());
        if (fundNetValue == null) {
            result.setSuccess(false);
            result.setErrorMessage("基金信息不存在，请确认基金代码！");
            return result;
        }
        String fundName = fundNetValue.getChiNameAbbr();
        Lookup lookup;
        if (isEdit == 0) {
            lookup = lookupService.getOrganBaby(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO, fundCode);
            if (lookup != null) {
                result.setSuccess(false);
                result.setErrorMessage("基金信息已存在！");
                return result;
            }
            lookup = new Lookup();
            lookup.setRuleValue(fundCode);
            lookup.setRuleType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
            lookup.setRuleText(fundName);
            lookup.setRuleValid(false);
            String ruleLimitValue = "{\"org\":{\"reminder\":\"" + reminder + "\",\"minMoney\":\"" + minValue + "\"}}";
            lookup.setRuleLimitValue(ruleLimitValue);
            try {
                organBabyService.addOrganBaby(lookup);
            } catch (Exception e) {
                result.setSuccess(false);
                e.printStackTrace();
            }
        } else {
            lookup = lookupService.getOrganBaby(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO, fundCode);
            lookup.setRuleValue(fundCode);
            lookup.setRuleType(RuleConstant.RULE_LOOKUP_TYPE_ORGAN_BAO);
            lookup.setRuleText(fundName);
            lookup.setRuleValid(false);
            String ruleLimitValue = "{\"org\":{\"reminder\":\"" + reminder + "\",\"minMoney\":\"" + minValue + "\"}}";
            lookup.setRuleLimitValue(ruleLimitValue);
            try {
                organBabyService.updateOrganBaby(lookup);
            } catch (Exception e) {
                result.setSuccess(false);
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 获取经办人列表
     *
     * @return
     */
    @GetMapping("/getAgents")
    public BaseResult getOrganAgents(String profileName, Integer pageIndex, Integer pageSize) {
        BaseListResult baseResult = new BaseListResult();
        List<OrganAgent> organAgentList = organAgentDao.findAll(profileName, 1, GlobalConstant.MAX_REQUEST_NUM);

        List<OrganAgent> organAgents = new ArrayList<>();
        baseResult.setTotalCount((long) organAgentList.size());
        baseResult.setRowCount(Long.valueOf(pageSize));
        for (int i = 0; i < organAgentList.size(); i++) {
            if (i >= (pageIndex - 1) * pageSize && i < pageSize * pageIndex) {
                organAgents.add(organAgentList.get(i));
            }
        }
        List<OrganAgentVo> resultVo = new ArrayList<>();
        organAgents.forEach(organAgent -> {
            List<OrganProfile> organProfile = organProfileService.queryListByAgentId(organAgent.getAgentId());
            OrganAgentVo organAgentVo = new OrganAgentVo(organAgent);
            organProfile.forEach(organProfile1 -> {
                organAgentVo.setProfileId(organProfile1.getProfileId().toString());
                organAgentVo.setProfileName(organProfile1.getCompanyName());
            });
            resultVo.add(organAgentVo);
        });
        baseResult.setResult(resultVo);
        return baseResult;
    }


    /**
     * 更新企业经办人信息
     *
     * @param agentId
     * @param name
     * @param mobile
     * @param idCard
     * @return
     */
    @PostMapping("/update/agent")
    public BaseResult updateAgent(String agentId, String name, String mobile, String idCard) {
        BaseResult baseResult = new BaseResult();
        OrganAgent organAgent = organAgentDao.selectByPrimaryKey(Long.valueOf(agentId));
        if (organAgent == null) {
            baseResult.setSuccess(false);
            baseResult.setResult("经办人信息不存在");
            return baseResult;
        }
        organAgent.setLastupdateTime(new Date());
        if (StringUtils.isNotBlank(name)) {
            organAgent.setOrganAgentMobile(mobile);
        }
        if (StringUtils.isNotBlank(mobile)) {
            organAgent.setOrganAgentName(name);
        }
        if (StringUtils.isNotBlank(idCard)) {
            organAgent.setOrganAgentIdcard(idCard);
        }
        organAgentDao.updateByPrimaryKeySelective(organAgent);
        baseResult.setResult(organAgent);
        return baseResult;
    }

    /**
     * 后台机构银行卡list
     *
     * @return
     */
    @GetMapping("/bank/list")
    public BaseResult organList(String profileName, String state, Integer pageIndex, Integer pageSize) {
        BaseListResult baseResult = new BaseListResult();
        List<OrganBank> allOrganBank = organBankService.getAll(profileName, state, 1, GlobalConstant.MAX_REQUEST_NUM);
        List<OrganBank> organBanks = new ArrayList<>();
        baseResult.setTotalCount((long) allOrganBank.size());
        baseResult.setRowCount(Long.valueOf(pageSize));
        for (int i = 0; i < allOrganBank.size(); i++) {
            if (i >= (pageIndex - 1) * pageSize && i < pageSize * pageIndex) {
                organBanks.add(allOrganBank.get(i));
            }
        }
        List<OrganBankVo> organBankVos = new ArrayList<>();
        for (OrganBank organBank : organBanks) {
            OrganProfile organProfile = organProfileService.getById(organBank.getProfileId());
            OrganBankVo organBankVo = new OrganBankVo(organBank);
            organBankVo.setProfileName(organProfile.getCompanyName());
            organBankVos.add(organBankVo);
        }
        baseResult.setResult(organBankVos);
        return baseResult;
    }


    /**
     * 审核机构银行卡
     *
     * @param organBankId 银行卡id
     * @param state       0 不同意  1 同意
     * @return
     */
    @GetMapping("/bank/check")
    public BaseResult checkOrganBank(String organBankId, String state) {
        BaseResult baseResult = new BaseResult();
        // 银行卡 auditStatus 审核状态  0=未审核  1=审核通过  2=审核未通过
        /*
         * 1. 获取机构银行卡相关信息，机构法人，机构经办人
         * 2. 请求恒生接口，返回成功 增开机构银行卡成功，失败则失败
         */
        OrganBank organBank = organBankService.getById(Long.valueOf(organBankId));
        if (organBank == null) {
            baseResult.setSuccess(false);
            baseResult.setResult(MessageUtil.getErrorMsg(ErrorConstant.ORGAN_BANK_NULL));
            return baseResult;
        }
        OrganProfile organProfile = organProfileService.getById(organBank.getProfileId());
        if (organProfile == null) {
            baseResult.setSuccess(false);
            baseResult.setResult(MessageUtil.getErrorMsg(ErrorConstant.ORGAN_PROFILE_NULL));
            return baseResult;
        }
        OrganAgent organAgent = organAgentDao.selectByPrimaryKey(organProfile.getOrganAgentId());
        if (organAgent == null) {
            baseResult.setSuccess(false);
            baseResult.setResult("机构经办人信息不存在");
            return baseResult;
        }
        User user = userService.getUser(organBank.getUserId());
        if (EqualsUtil.equals("1", state)) {
            // 请求恒生接口 增开银行卡
            try {
                AccountModel accountModel = queryService.getMainAccount(organProfile.getExternalClientId());
                if (accountModel == null || StringUtil.isEmpty(accountModel.getTradeAccount())) {
                    baseResult.setSuccess(false);
                    baseResult.setErrorCode(ErrorConstant.ERROR_NO_MAIN_ACCOUNT_FIND);
                    baseResult.setErrorType(GlobalConstant.ERROR_TYPE_APPLICATION);
                    return baseResult;
                }
                // 组装请求参数
                String mainTradeAccount = accountModel.getTradeAccount();
                Map<String, String> params = new HashMap<>();
                params.put("mainTradeAccount", mainTradeAccount);
                params.put("mobile", user.getUserMobile());
                params.put("agentName", organAgent.getOrganAgentName());
                params.put("tradePassword", organBank.getTradePassword());
                params.put("agentIdNo", organAgent.getOrganAgentIdcard());
                params.put("agentMobile", organAgent.getOrganAgentMobile());
                params.put("bankCode", organBank.getUbBankNo());
                params.put("bankName", organBank.getUbBankBranchName());
                params.put("accName", organBank.getUbOrganBankOwner());
                params.put("bankNo", organBank.getUbOrganBankNo());
                params.put("capitalMode", "1");
                params.put("companyName", organProfile.getCompanyName());
                params.put("branchBank", organBank.getUbBranchbank());
                params.put("idNo", user.getUserCard());
                Map<String, Object> result = tradeAccountAddAcctService.organAddAcc(params);
                // 接收恒生返回结果
                if (HsResponseUtil.isOperationOk(result)) {
                    organBank.setAuditStatus(1);
                    organBank.setExternalTradeAccount(result.get(HSOutputParameterNames.TRADE_ACCO) + "");
                    organBankService.updateOrganBank(organBank);
                    return baseResult;
                } else {
                    baseResult.setSuccess(true);
                    baseResult.setResult(result.get(HSOutputParameterNames.ERROR_INFO) + "");
                    organBank.setAuditStatus(2);
                    log.error("审核机构银行卡失败");
                    organBankService.updateOrganBank(organBank);
                    return baseResult;
                }
            } catch (Exception e) {
                baseResult.setSuccess(false);
                log.error("审核机构银行卡失败，错误信息：{}", e.getMessage());
                e.printStackTrace();
                return baseResult;
            }

        } else if (EqualsUtil.equals("0", state)) {
            organBank.setAuditStatus(2);
            organBankService.updateOrganBank(organBank);
            return baseResult;
        } else {
            baseResult.setSuccess(false);
            baseResult.setResult("请求参数错误 state = " + state);
            return baseResult;
        }
    }

}




